package io.renren.modules.hospital.service.impl;

import io.renren.common.exception.RRException;
import io.renren.common.validator.Assert;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.hospital.entity.YsEntity;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.hospital.dao.EmrYsInfoDao;
import io.renren.modules.hospital.entity.EmrYsInfoEntity;
import io.renren.modules.hospital.service.EmrYsInfoService;


@Service("emrYsInfoService")
public class EmrYsInfoServiceImpl extends ServiceImpl<EmrYsInfoDao, EmrYsInfoEntity> implements EmrYsInfoService {

    @Autowired
    EmrYsInfoDao ysInfoDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<EmrYsInfoEntity> page = this.page(
                new Query<EmrYsInfoEntity>().getPage(params),
                new QueryWrapper<EmrYsInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public EmrYsInfoEntity queryByPhone(String phone) {
        return baseMapper.selectOne(new QueryWrapper<EmrYsInfoEntity>().eq("EMR_ys_phone", phone));
    }

    @Override
    public long login(LoginForm form) {
        EmrYsInfoEntity user = queryByPhone(form.getMobile());
        Assert.isNull(user, "手机号或密码错误");

        //密码错误
        if(!user.getEmrYsPwd().equals(DigestUtils.sha256Hex(form.getPassword()))){
            throw new RRException("手机号或密码错误");
        }

        return user.getEmrYsId();
    }

    /**
     * 根据科室名称查找该科室下的所有医生
     * @return 医生列表
     */
    @Override
    public List<EmrYsInfoEntity> getYsListBySection(String ysSection) {
        return ysInfoDao.getYsListBySection(ysSection);
    }

    @Override
    public List<EmrYsInfoEntity> getBbsListByParam(String key, String paramType, int page, int size) {
        List<EmrYsInfoEntity> res = new ArrayList<>();
        if (paramType.equals("EMR_ys_id"))
            res = ysInfoDao.getYsListByYsId(key , (page - 1) * size, size);
        if (paramType.equals("EMR_ys_name"))
            res = ysInfoDao.getYsListByYsName('%' + key + '%', (page - 1) * size, size);
        if (paramType.equals("EMR_ys_phone"))
            res = ysInfoDao.getYsListByYsPhone('%' + key + '%', (page - 1) * size, size);
        if (paramType.equals("EMR_ys_section"))
            res = ysInfoDao.getYsListByYsSection('%' + key + '%', (page - 1) * size, size);
        return res;
    }

}
